import { useState, useCallback, useEffect, useMemo } from "react";
import { Form, Input, Button, Table, message, Image, Badge } from "antd";
import { ColumnsType } from "antd/es/table";
import { useForm } from "antd/es/form/Form";

import "./user.css";

import { userSearch, freeze } from "../../api/user";

interface SearchUser {
    username: string;
    nickname: string;
    email: string;
}
export interface UserSearchResult {
    id: number;
    username: string;
    nickName: string;
    email: string;
    headPic: string;
    createTime: Date;
    isFrozen: boolean;
}

export function UserManager() {
    const [pageNo, setPageNo] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [userResult, setUserResult] = useState<UserSearchResult[]>([]);
    const [num, setNum] = useState(0);

    // 实现刷新后，保留现有的搜索条件
    const [form] = useForm();

    useEffect(()=>{
        searchUser({ username: form.getFieldValue("username"), nickname: form.getFieldValue("nickName"), email: form.getFieldValue("email") });
    }, [pageNo, pageSize, num]);

    const changePage = useCallback((pageNo: number, pageSize: number)=>{
        setPageNo(pageNo);
        setPageSize(pageSize);
    }, [])

    const searchUser = useCallback(async (values: SearchUser)=>{
        const { username, nickname, email } = values;
        const res = await userSearch(username, nickname, email, pageNo, pageSize);
        if(res.status === 200 || res.status === 201) {
            setUserResult(res.data.users);
        }else {
            message.error("系统繁忙，请稍后重试");
        }
    }, []);

    const columns: ColumnsType<any> = useMemo(()=>(
        [
            {
                title: "用户名",
                dataIndex: "username"
            },
            {
                title: "头像",
                dataIndex: "headPic",
                render: value => {
                    return value ? <Image width={50} src={`http://localhost:3005/${value}`} /> : ''
                }
            },
            {
                title: "昵称",
                dataIndex: "nickName"
            },
            {
                title: "邮箱",
                dataIndex: "email"
            },
            {
                title: "注册时间",
                dataIndex: "createTime"
            },
            {
                title: "状态",
                dataIndex: "isFrozen",
                render: (_, record)=>(record.isFrozen ? <Badge status="success">已冻结</Badge>:'')
            },
            {
                title: "操作",
                render: (_, record) => (<a href="#" onClick={()=>{freezeUser(record.id)}}></a>)
            }
        ] 
    ),[])


    const freezeUser = useCallback((id: number)=>{
        freeze(id).then(res => {
            if(res.data === 201 || res.status === 200) {
                message.success("冻结成功");
                setNum(Math.random());
            }
        }, err => {
            message.error(err);
        })
    }, [])

    return (
        <div className="user">
            <div className="user__form">
                <Form name="search"
                    form={form}
                    layout="inline"
                    colon={false}
                    onFinish={searchUser}
                >
                    <Form.Item label="用户名" name="username">
                        <Input></Input>
                    </Form.Item>
                    <Form.Item label="昵称" name="nickName">
                        <Input></Input>
                    </Form.Item>
                    <Form.Item label="邮箱" name="email">
                        <Input></Input>
                    </Form.Item>
                    <Form.Item label=" ">
                        <Button type="primary" htmlType="submit">搜索用户</Button>
                    </Form.Item>
                </Form>
            </div>
            <div className="user__table">
                <Table columns={columns} dataSource={userResult} pagination={{ current: pageNo, pageSize, onChange: changePage }}></Table>
            </div>
        </div>
    )
}